define(function (require, exports, module) {
    // require('./plug/hammer.min');
    // require('./plug/layer/layer');
    var myPub = require('./public');
    var base64 = require('./plug/base64');

    // 搜索设置cookie
    var cTime = 'd7';       // coookie 时间
    var _val = [];
    var oMessageIcon = $('.js_messageIcon');			// 首页消息图标
    var oSearchBox = $('.js_searchBox');    	        // 搜索区域
    var oSearchRecom = $('.js_searchRecom');			// 搜索推荐
    var oSearchBtn = $('.js_searchBtn');    	        // 搜索按钮
    var oSearchTxt = $('.js_searchTxt');    	        // 搜索框
    var oHClearBtn = $('.js_HClearBtn');  		        // 清楚历史记录按钮
    var oHisListUl = $('.js_hisList').find('ul'); 		// 历史记录UL
    var recomHTMl = oHisListUl.html();                  // 系统推荐
    var cookArry = document.cookie.split('; ');   		// 分离cookie成数组
    var cookIndex = parseInt(myPub.getCookie('cookIndex')); // 记录个数
    var oShadow = $('.js_shadow');				// 阴影
    var oHotList = $('.js_hotList');		    // 热门列表
    var oClearBtn = $('.js_clearBtn'); 		    // 清除按钮
    var oSearchForm = $('#searchForm');		    // 提交的表单

    var oMessageIconHrefBtn = $('.js_messageIconHrefBtn');		    // 弹层搜索按钮

    var oShowSearchBox = $('.js_showSearchBox');                    // 搜索图标按钮

    var maxCookieNum = 4;

    //取消滑动 
    oSearchRecom.on("touchmove", function (e) {
        e.preventDefault()
    });

    oSearchTxt.on('focus', function () {
        //oMessageIcon.hide();
        oSearchRecom.show();
        oShadow.show().css({'top': oSearchBox.outerHeight(true)});
    });

    oSearchTxt.on('blur', function () {
        //oMessageIcon.show();
        oSearchRecom.hide();
        oShadow.hide().css({'top': 0});
    });

    // 弹层消息按钮点击跳转
    oMessageIconHrefBtn.hammer().on('tap',function() {
        var _href =  oMessageIconHrefBtn.find('a').attr('href');
        myPub.locationHref(_href)
    });


    $('#form').submit(function () {
        return false
    });

    // 搜索图标按钮点击
    oShowSearchBox.on('click',function (e) {
        oSearchRecom.show();
        oSearchTxt.focus();
        e.stopPropagation();
    });

    // 阴影关闭
    oShadow.on('click',function (e) {
        //失去焦点
        oSearchTxt.blur();
        oSearchRecom.hide();
        e.stopPropagation();
    });


    // // 获取cookie并设置历史记录
    // if (myPub.getCookie('cookIndex') == undefined || myPub.getCookie('cookIndex') == -1) {
    //     myPub.setCookie('cookIndex', '-1', cTime);
    //     cookIndex = parseInt(myPub.getCookie('cookIndex'));
    // }
    // else {
    //     oHisListUl.empty();
    //     for (var i = 0; i < cookArry.length; i++) {
    //         if (cookArry[i].charAt(0) == 'r') {
    //             _val[i] = cookArry[i].substring(cookArry[i].indexOf('=') + 1);
    //             oHisListUl.prepend('<li><span>' + unescape(_val[i]) + '</span></li>');
    //         }
    //     }
    // }

    //获取cookie并设置历史记录
    var searchListBase64 = myPub.getCookie('searchList')
    if (searchListBase64 != null && searchListBase64 != '') {
        var searchList = JSON.parse(base64.decode(searchListBase64))
        for (var i = 0; i < searchList.length; i++) {
            var obj = searchList[i]
            if (obj.isLink) {
                if (obj.isSign)
                    oHisListUl.prepend('<li><span class="active" data-type="yes" data-id="' + obj.link + '">' + obj.word + '</span></li>')
                else
                    oHisListUl.prepend('<li><span data-type="yes" data-id="' + obj.link + '">' + obj.word + '</span></li>')
            }
            else {
                if (obj.isSign)
                    oHisListUl.prepend('<li><span class="active">' + obj.word + '</span></li>')
                else
                    oHisListUl.prepend('<li><span>' + obj.word + '</span></li>')
            }
        }
    }

    //搜索后添加cookie
    oSearchBtn.hammer().on('tap', function () {
        JumpSearchPage();
    });
    //键盘事件
    $(document).keydown(function (event) {
        if (event.keyCode == 13) {
            var isLink = $('#keyword').attr('data-id')
            var h5link = $('#keyword').attr('data-type')
            var searchWord = $('#keyword').attr('placeholder')
            var input = $('#keyword').val()

            if (input != '') {
                //保存搜索历史到cookie
                saveHistory({
                    word: input,
                    isLink: false,
                    link: '',
                    isSign: false
                })
                window.location.href =  '../../shop/goods/tosearchv3?keyword=' + input
            }
            else {
                if (isLink == 'true') {
                    saveHistory({
                        word: searchWord,
                        isLink: true,
                        link: h5link,
                        isSign: false
                    })
                    window.location.href = h5link
                }
                else {
                    saveHistory({
                        word: searchWord,
                        isLink: false,
                        link: '',
                        isSign: false
                    })
                    window.location.href =  '../../shop/goods/tosearchv3?keyword=' + searchWord
                }
            }
        }
    });

    function saveHistory(obj) {
        var searchListBase64 = myPub.getCookie('searchList'), searchList = [], finalList = []
        if (searchListBase64 == null || searchListBase64 == '')
            searchList = []
        else searchList = JSON.parse(base64.decode(searchListBase64))
        var isContain = false;
        for (var i = 0; i < searchList.length; i++) {
            if (searchList[i].word == obj.word)
                isContain = true
        }
        if (isContain)
            return
        searchList.push(obj)
        var jsonListBase64 = base64.encode(JSON.stringify(searchList))
        myPub.setCookie('searchList', jsonListBase64)
    }

    function clearHistory() {
        myPub.setCookie('searchList', '')
        oHisListUl.html('')
    }

    // 清除cookie和历史记录
    oHClearBtn.hammer().on('tap', function () {
        //失去焦点
        oSearchTxt.blur();
        myPub.askLayer('亲！您确定要清除历史记录？', function () {
            // for (var i = 0; i < cookArry.length; i++) {
            //     myPub.delCookie('records' + i);
            // }
            // myPub.delCookie('cookIndex');
            // // 清楚cookie的记录 添加系统推荐的
            // oHisListUl.empty().html(recomHTMl);
            clearHistory();
            myPub.LayerCloseAll();
        }, function () {
            myPub.LayerCloseAll();
        }, 'no');
    });

    //热门搜索点击
    oHotList.hammer().on('tap', function (e) {
        oSearchTxt.blur();
        var _tarTag = e.gesture.target;
        var target, tarTxt;
        _tarTag.nodeName.toLowerCase() == 'li' ? target = $(_tarTag) : target = $(_tarTag).parents('li');
        tarTxt = target.find('span').text();
        target.parents('ul').find('li').removeClass('active');
        target.addClass('active');
        if (tarTxt !== '') {
            oSearchTxt.val(tarTxt);
            oClearBtn.show();
            var isLink = target.find('span').attr('data-type'), link = target.find('span').attr('data-id'),
                isActive = target.find('span').hasClass("active")
            JumpSearchPage('hotwords', isLink, link, tarTxt, isActive);
        }
        myPub.HamstopPropaga()
        e.stopPropagation();

    });

    //历史记录搜索点击
    oHisListUl.hammer().on('tap', function (e) {
        oSearchTxt.blur();
        var _tarTag = e.gesture.target;
        var target, tarTxt, isActive, isLink, link;
        JumpSearchPage('', $(_tarTag).attr('data-type'), $(_tarTag).attr('data-id'), $(_tarTag).text(), $(_tarTag).hasClass('active'))
        // if (tarTxt !== '') {
        //     oSearchTxt.val(tarTxt);
        //     oClearBtn.show();
        //     JumpSearchPage();
        // }
        //
        myPub.HamstopPropaga()
        e.stopPropagation();
    });

    //跳转搜索结果
    function JumpSearchPage(searchType, isLink, link, text, isActive) {
        // if (oSearchTxt.val() == '') {
        //     //myPub.TipLayer('亲！搜索信息不能为空！');
        //     /oSearchFormSub();
        // }
        // else if (oSearchTxt.val().indexOf('<') > 0 || oSearchTxt.val().indexOf('>') > 0) {
        //     return
        // }
        // 检测是否有相同的产品

        // for (var i = 0; i < maxCookieNum; i++) {
        //     if (oSearchTxt.val() == myPub.getCookie('records' + i)) {
        //         //console.log('有相同名字')
        //         oSearchFormSub();
        //         return;
        //     }
        //
        // }

        // cookIndex == null || cookIndex >= maxCookieNum ? cookIndex = 0 : cookIndex++;
        // myPub.setCookie('records' + cookIndex, oSearchTxt.val(), cTime);
        // myPub.setCookie('cookIndex', cookIndex, cTime);
        if (isLink == 'yes') {
            saveHistory({
                word: text,
                isLink: true,
                link: link,
                isSign: isActive
            })
            window.location.href = link
        }
        else {
            saveHistory({
                word: text,
                isLink: false,
                link: '',
                isSign: isActive
            })
            window.location.href = '../../shop/goods/tosearchv3?keyword=' + text
        }
    }


    //延迟提交
    function oSearchFormSub() {
        var subTime;
        clearTimeout(subTime)
        subTime = setTimeout(function () {
            oSearchForm.submit();
        }, 300)
    }

    function getSearchWord() {
        G_JSON_GET('/search/searchWord', '', function (response) {
            try {
                if (response.status == 200) {
                    $('#keyword').attr('placeholder', response.searchWord.name)
                    $('#keyword').attr('data-id', response.searchWord.searchType)
                    $('#keyword').attr('data-type', response.searchWord.h5link)
                }
            } catch (e) {

            }
        })
    }

    function getHotWords() {
        G_JSON_GET('/search/hotWords', null, function (response) {
            try {
                if (response.length > 0) {
                    var list = response
                    for (var i = 0; i < list.length; i++) {
                        var name = list[i].name, isSign = list[i].isSign, searchType = list[i].searchType,
                            h5link = list[i].h5link
                        if (isSign) {
                            if (searchType)
                                $('.js_hotList').append('<li><span class="active" data-type="yes" data-id="' + h5link + '">' + name + '</span></li>')
                            else
                                $('.js_hotList').append('<li><span class="active" data-type="no">' + name + '</span></li>')
                        }
                        else {
                            if (searchType)
                                $('.js_hotList').append('<li><span data-type="yes" data-id="' + h5link + '">' + name + '</span></li>')
                            else
                                $('.js_hotList').append('<li><span data-type="no">' + name + '</span></li>')
                        }
                    }
                }
            } catch (e) {

            }
        })
    }

    getHotWords();
    getSearchWord();

});